package com.android.launcher3.widget;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.launcher3.AppInfo;
import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.manager.WidgetManager;
import com.android.launcher3.touch.ItemClickHandler;
import com.x.component.framework.ActivityManagerWrapper;

public class RecommendWidget extends FrameLayout {
    private ViewGroup mContainer;
    private ImageView mImageViewSingle;
    private ImageButton mFirstImage;
    private ImageButton mSecondImage;
    private TextView mSpiltScreen1;
    private TextView mSpiltScreen2;
    private HotSeatAppWidget app1;
    private HotSeatAppWidget app2;
    private HotSeatAppWidget app3;
    private HotSeatAppWidget app4;
    private View spiltLayout1;
    private View spiltLayout2;

    private int id = 0;

    private boolean full = false;

    AddWidgetPopWindow.WidgetData widgetData1;
    AddWidgetPopWindow.WidgetData widgetData2;

    public RecommendWidget(@NonNull Context context) {
        super(context);
        init(null);
    }

    public RecommendWidget(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public RecommendWidget(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    void init(@Nullable AttributeSet attrs) {


        if (attrs != null) {
            TypedArray a = getContext().getTheme().obtainStyledAttributes(
                    attrs,
                    R.styleable.RecommendWidget,
                    0, 0);
            try {
                id = a.getInteger(R.styleable.RecommendWidget_recommend_id, 0);
                full = a.getBoolean(R.styleable.RecommendWidget_recommend_full, false);
            } finally {
                a.recycle();
            }

        }
        LayoutInflater.from(getContext()).inflate(R.layout.layout_recommend, this, true);
        mContainer = findViewById(R.id.container);
        mImageViewSingle = findViewById(R.id.image_view_single);
        mFirstImage = findViewById(R.id.v_first_image);
        mSecondImage = findViewById(R.id.v_second_image);

        mSpiltScreen1 = findViewById(R.id.tv_split1);
        mSpiltScreen2 = findViewById(R.id.tv_split2);

        spiltLayout1 = findViewById(R.id.split_layout);
        spiltLayout2 = findViewById(R.id.split_layout2);

        app1 = findViewById(R.id.app1);
        app2 = findViewById(R.id.app2);
        app3 = findViewById(R.id.app3);
        app4 = findViewById(R.id.app4);

        if (full) {
            mImageViewSingle.setVisibility(VISIBLE);
            mFirstImage.setVisibility(INVISIBLE);
            mSecondImage.setVisibility(INVISIBLE);
        } else {
            mImageViewSingle.setVisibility(GONE);
            mFirstImage.setVisibility(VISIBLE);
            mSecondImage.setVisibility(VISIBLE);
        }

        if (isFull()) {
            mContainer.setLongClickable(true);
            mContainer.setOnLongClickListener(v -> {
                openChooseWidget(v, true);
                return true;
            });
        }

        if (isFull()) {
            mImageViewSingle.setOnClickListener(v -> {
                if (widgetData1 != null && widgetData1.packageName != null) {
                    openApp(widgetData1.packageName, v);
                }
            });
        }

        if (isFull()) {
            mImageViewSingle.setOnLongClickListener(v -> {
                openChooseWidget(v, true);
                return true;
            });
        }

        mFirstImage.setOnClickListener(v -> {
            if (widgetData1 != null && widgetData1.packageName != null) {
                openApp(widgetData1.packageName, v);
            }
        });

        mFirstImage.setOnLongClickListener(v -> {
            openChooseWidget(v, true);
            return true;
        });

        mSecondImage.setOnClickListener(v -> {
            if (widgetData2 != null && widgetData2.packageName != null) {
                openApp(widgetData2.packageName, v);
            }
        });

        mSecondImage.setOnLongClickListener(v -> {
            openChooseWidget(v, false);
            return true;
        });
        app1.setOnLongClickListener(v -> {
            openChooseWidget(v, true);
            return true;
        });
        app2.setOnLongClickListener(v -> {
            openChooseWidget(v, true);
            return true;
        });
        app3.setOnLongClickListener(v -> {
            openChooseWidget(v, false);
            return true;
        });
        app4.setOnLongClickListener(v -> {
            openChooseWidget(v, false);
            return true;
        });

        spiltLayout1.setOnLongClickListener(v -> {
            openChooseWidget(v, true);
            return true;
        });

        spiltLayout2.setOnLongClickListener(v -> {
            openChooseWidget(v, false);
            return true;
        });


        Launcher launcher = Launcher.getLauncher(getContext());

        app1.setOnClickListener(v -> AddAppPopWindow.INSTANT.show(launcher, launcher.getAppsView().getAppsStore().getAppsList(), appInfo -> {
            app1.setAppInfo(appInfo);
            if (appInfo != null && appInfo.componentName != null) {
                WidgetManager.WidgetStoreData widgetStoreData = new WidgetManager.WidgetStoreData(id);
                widgetStoreData.spiltApp1Package = appInfo.componentName.getPackageName();
                WidgetManager.INSTANCE.save(widgetStoreData);
            }
        }));
        app2.setOnClickListener(v -> AddAppPopWindow.INSTANT.show(launcher, launcher.getAppsView().getAppsStore().getAppsList(), appInfo -> {
            app2.setAppInfo(appInfo);
            if (appInfo != null && appInfo.componentName != null) {
                WidgetManager.WidgetStoreData widgetStoreData = new WidgetManager.WidgetStoreData(id);
                widgetStoreData.spiltApp2Package = appInfo.componentName.getPackageName();
                WidgetManager.INSTANCE.save(widgetStoreData);
            }
        }));

        app3.setOnClickListener(v -> AddAppPopWindow.INSTANT.show(launcher, launcher.getAppsView().getAppsStore().getAppsList(), appInfo -> {
            app3.setAppInfo(appInfo);
            if (appInfo != null && appInfo.componentName != null) {
                WidgetManager.WidgetStoreData widgetStoreData = new WidgetManager.WidgetStoreData(id);
                widgetStoreData.spiltApp3Package = appInfo.componentName.getPackageName();
                WidgetManager.INSTANCE.save(widgetStoreData);
            }
        }));
        app4.setOnClickListener(v -> AddAppPopWindow.INSTANT.show(launcher, launcher.getAppsView().getAppsStore().getAppsList(), appInfo -> {
            app4.setAppInfo(appInfo);
            if (appInfo != null && appInfo.componentName != null) {
                WidgetManager.WidgetStoreData widgetStoreData = new WidgetManager.WidgetStoreData(id);
                widgetStoreData.spiltApp4Package = appInfo.componentName.getPackageName();
                WidgetManager.INSTANCE.save(widgetStoreData);
            }
        }));


        mSpiltScreen1.setOnClickListener(view -> {
            Log.d("TinkerSplit", "onClick");
            AppInfo appInfo1 = app1.getAppInfo();
            AppInfo appInfo2 = app2.getAppInfo();
            if (appInfo1 != null && appInfo1.componentName != null && appInfo2 != null && appInfo2.componentName != null) {
                Log.d("TinkerSplit", "onClick appInfo1: " + appInfo1.componentName.getPackageName());
                Log.d("TinkerSplit", "onClick appInfo2: " + appInfo2.componentName.getPackageName());
                try {
                    ActivityManagerWrapper.getInstance().startActivityInSplitScreen(appInfo1.intent, true, 0.5f,
                            appInfo2.intent, true, 0.5f);
                } catch (Throwable t) {
                    t.printStackTrace();
                }

            }
        });

        mSpiltScreen2.setOnClickListener(view -> {
            Log.d("TinkerSplit", "onClick");
            AppInfo appInfo3 = app3.getAppInfo();
            AppInfo appInfo4 = app4.getAppInfo();
            if (appInfo3 != null && appInfo3.componentName != null && appInfo4 != null && appInfo4.componentName != null) {
                Log.d("TinkerSplit", "onClick appInfo3: " + appInfo3.componentName.getPackageName());
                Log.d("TinkerSplit", "onClick appInfo4: " + appInfo4.componentName.getPackageName());
                try {
                    ActivityManagerWrapper.getInstance().startActivityInSplitScreen(appInfo3.intent, true, 0.5f,
                            appInfo4.intent, true, 0.5f);
                } catch (Throwable t) {
                    t.printStackTrace();
                }

            }
        });
    }

    public void bindWidget() {

        WidgetManager.WidgetStoreData widgetStoreData = WidgetManager.INSTANCE.getWidgetStoreData(getId());
        if (widgetStoreData != null) {
            AddWidgetPopWindow.WidgetData widgetData1 = AddWidgetPopWindow.INSTANT.getWidgetData(isFull(), widgetStoreData.widgetId1);
            AddWidgetPopWindow.WidgetData widgetData2 = AddWidgetPopWindow.INSTANT.getWidgetData(isFull(), widgetStoreData.widgetId2);

            if (widgetData1 == null) {
                widgetData1 = AddWidgetPopWindow.INSTANT.getDefaultData(id, true);
            }
            if (widgetData2 == null && !isFull()) {
                widgetData2 = AddWidgetPopWindow.INSTANT.getDefaultData(id, false);
            }

            this.widgetData1 = widgetData1;
            this.widgetData2 = widgetData2;
            setData();
        } else {
            ///get default widget data
            this.widgetData1 = AddWidgetPopWindow.INSTANT.getDefaultData(id, true);
            this.widgetData2 = AddWidgetPopWindow.INSTANT.getDefaultData(id, false);
            setData();
        }
    }

    private void openChooseWidget(View v, boolean isTopHalf) {
        AddWidgetPopWindow.INSTANT.show(Launcher.getLauncher(getContext()), full, widgetData -> {
            WidgetManager.WidgetStoreData widgetStoreData = new WidgetManager.WidgetStoreData(id);
            if (isTopHalf) {
                this.widgetData1 = widgetData;
                widgetStoreData.widgetId1 = widgetData.id;
            } else {
                this.widgetData2 = widgetData;
                widgetStoreData.widgetId2 = widgetData.id;
            }
            WidgetManager.INSTANCE.save(widgetStoreData);
            setData();
        });
    }

    private void setData() {

        if (full && widgetData1 == null) return;

        if (!full && widgetData1 == null && widgetData2 == null) return;

        if (full) {
            mImageViewSingle.setImageResource(widgetData1.imageResId);
        } else {
            setHalfWidget(true, widgetData1);
            setHalfWidget(false, widgetData2);
        }

    }


    void setHalfWidget(boolean isTopHalf, @Nullable AddWidgetPopWindow.WidgetData widgetData) {

        ImageButton imageButton = isTopHalf ? mFirstImage : mSecondImage;

        HotSeatAppWidget firstApp = isTopHalf ? app1 : app3;
        HotSeatAppWidget secApp = isTopHalf ? app2 : app4;
        TextView mSpiltScreen = isTopHalf ? mSpiltScreen1 : mSpiltScreen2;
        if (widgetData != null && widgetData.type == AddWidgetPopWindow.WidgetType.half) {
            imageButton.setImageResource(widgetData.imageResId);
            firstApp.setVisibility(INVISIBLE);
            secApp.setVisibility(INVISIBLE);
            mSpiltScreen.setVisibility(INVISIBLE);
            imageButton.setVisibility(VISIBLE);
            spiltLayout1.setVisibility(GONE);
            spiltLayout2.setVisibility(GONE);
        } else if (widgetData != null && widgetData.type == AddWidgetPopWindow.WidgetType.split) {
            firstApp.setVisibility(VISIBLE);
            secApp.setVisibility(VISIBLE);
            mSpiltScreen.setVisibility(VISIBLE);
            imageButton.setVisibility(INVISIBLE);
            if (isTopHalf) {
                spiltLayout1.setVisibility(VISIBLE);
            } else {
                spiltLayout2.setVisibility(VISIBLE);
            }
            Launcher launcher = Launcher.getLauncher(getContext());

            WidgetManager.WidgetStoreData widgetStoreData = WidgetManager.INSTANCE.getWidgetStoreData(getId());
            if (widgetStoreData != null) {
                AppInfo appInfo1 = launcher.getAppsView().getAppsStore().getAppInfo(isTopHalf ? widgetStoreData.spiltApp1Package : widgetStoreData.spiltApp3Package);
                AppInfo appInfo2 = launcher.getAppsView().getAppsStore().getAppInfo(isTopHalf ? widgetStoreData.spiltApp2Package : widgetStoreData.spiltApp4Package);

                if (appInfo1 != null) {
                    firstApp.setAppInfo(appInfo1);
                }
                if (appInfo2 != null) {
                    secApp.setAppInfo(appInfo2);
                }
            }
        }
    }

    void openApp(@NonNull String packageName, View view) {
        ///要在launcher activity里
        Launcher launcher = Launcher.getLauncher(getContext());

        ///可能为空
        AppInfo appInfo = launcher.getAppsView().getAppsStore().getAppInfo(packageName);

        if (appInfo != null) {
            view.setTag(appInfo);
            ItemClickHandler.INSTANCE.onClick(view);
        } else {
            ///跳应用市场
            try {
                intoGooglePlayInstall(packageName);
            } catch (Exception e) {
            }
        }

    }

    public void intoGooglePlayInstall(String pkg) {
//        final String GOOGLE_PLAY = "com.android.vending";
        final String GOOGLE_PLAY = "com.apkpure.aegon";
        //final String YINGYONGBAO = "com.tencent.android.qqdownloader";
        if (TextUtils.isEmpty(pkg)) {
            return;
        }
        try {
            Uri uri = Uri.parse("market://details?id=" + pkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage(GOOGLE_PLAY);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);

        } catch (Exception exception) {

        }
    }

    @Override
    public int getId() {
        return id;
    }

    public boolean isFull() {
        return full;
    }
}
